/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.infrastructure.message.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.errors.SerializationException;

import java.io.*;

/**
 * CodecUtil
 *
 * @author anle5
 * @since 2024/7/28 15:04
 */
@Slf4j
public class CodecUtil {
    /**
     * 对象序列化为byte数组
     *
     * @param ori obj
     * @return byte[]
     */
    public static byte[] bean2Byte(Object ori) {
        try (ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
             ObjectOutputStream outputStream = new ObjectOutputStream(byteArray)) {
            outputStream.writeObject(ori);
            outputStream.flush();
            return byteArray.toByteArray();
        } catch (IOException e) {
            log.error("Bean2Byte [{}] -> [bytes] transfer failed.", ori.getClass(), e);
            throw new SerializationException(e);
        }
    }

    /**
     * 字节数组转为Object对象
     *
     * @param bytes bytes
     * @return Object
     */
    public static Object byte2Obj(byte[] bytes) {
        Object readObject = new Object();
        try (ByteArrayInputStream in = new ByteArrayInputStream(bytes);
             ObjectInputStream inputStream = new ObjectInputStream(in)) {
            return inputStream.readObject();
        } catch (Exception e) {
            log.error("Bean2Byte [bytes] -> [{}] transfer failed.", readObject.getClass(), e);
            throw new SerializationException(e);
        }
    }
}
